package com.wolfking.gateway;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.hateoas.VndErrors.VndError;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import io.jmnarloch.spring.request.correlation.support.RequestCorrelationUtils;

/**
 * 解决Zuul对某些异常返回200
 * <P>
 * 且无返回内容的问题
 * 
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年4月19日下午2:46:41
 * @版权 归wolfking所有
 */
@RestController
public class VndErrorController implements ErrorController {

	@Value("${error.path:/error}")
	private String errorPath;

	@Override
	public String getErrorPath() {
		return errorPath;
	}

	@RequestMapping(value = "${error.path:/error}", produces = "application/vnd.error+json")
	public ResponseEntity<VndError> error(HttpServletRequest request) {
		final String logref = RequestCorrelationUtils.getCurrentCorrelationId();
		final int status = getErrorStatus(request);
		final String errorMessage = getErrorMessage(request);
		final VndError error = new VndError(logref, errorMessage);
		return ResponseEntity.status(status).body(error);
	}

	private int getErrorStatus(HttpServletRequest request) {
		Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
		return statusCode != null ? statusCode : HttpStatus.INTERNAL_SERVER_ERROR.value();
	}

	private String getErrorMessage(HttpServletRequest request) {
		final Throwable ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
		return ex != null ? ex.getMessage() : "Unexpected ERROR occurred!";
	}

}
